package com.lhn.locks;

/**
 * 〈一句话功能简述>
 * 〈一定会发生死锁的情况〉
 *
 * @Author 17505
 * @Create 2022/3/4
 * @Since 1.0.0
 */
public class MustDeadLock extends Thread {
    int flag = 1;
    static Object o1 = new Object();
    static Object o2 = new Object();

    public static void main(String[] args) {
        MustDeadLock run1 = new MustDeadLock();
        MustDeadLock run2 = new MustDeadLock();
        run1.flag = 1;
        run2.flag = 0;
        run1.start();
        run2.start();
    }

    @Override
    public void run() {
        System.out.println("flag = " + flag);
        if (flag == 1) {
            synchronized (o1) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("线程1成功拿到两把锁!");
                }
            }
        }
        if (flag == 0) {
            synchronized (o2) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println("线程2成功拿到两把锁!");
                }
            }
        }
    }
}